﻿using System.Collections.Specialized;
using System.Linq;

namespace N2.BlogEngine.Providers
{
	using global::BlogEngine.Core.Providers;
	using N2;
	using n2 = N2.BlogEngine;
	
	public partial class N2BlogProvider: BlogProvider
	{
		#region Blog Settings

		StringDictionary TryLoadingSettings()
		{
			var _result = new StringDictionary();

			n2.BlogService.CurrentBlog.Settings
				.ToList()
				.ForEach(_item => _result.Add(_item.Key, _item.Value));

			return _result;
		}

		public override StringDictionary LoadSettings()
		{
			var _result = this.TryLoadingSettings();
			
			if (0 == _result.Count && this.UseFallBackProvider) {
				//install defaults from xml
				this.SaveSettings(FallBackProvider.LoadSettings());
				_result = this.TryLoadingSettings();
			}

			return _result;
		}

		public override void SaveSettings(StringDictionary settings)
		{
			var _settings = n2.BlogService.CurrentBlog.Settings;

			foreach(string _name in settings.Keys) {
				_settings[_name] = settings[_name];
			}

			Context.Persister.Save(n2.BlogService.CurrentBlog);
		}

		#endregion Blog Settings

		#region Ping services

		public override StringCollection LoadPingServices()
		{
			var _settings = new StringCollection();
			
			_settings.AddRange(n2.BlogService.CurrentBlog.PingServices.ToArray());
			
			return _settings;
		}

		public override void SavePingServices(StringCollection services)
		{
			var _services = n2.BlogService.CurrentBlog.PingServices;
			_services.Clear();
			
			services.Cast<string>().ToList().ForEach(_services.Add);
			
			Context.Persister.Save(n2.BlogService.CurrentBlog);
		}

		#endregion Ping services

		#region Stop words

		public override StringCollection LoadStopWords()
		{
			var _stopWords = new StringCollection();
			_stopWords.AddRange(n2.BlogService.CurrentBlog.StopWords.ToArray());
			return _stopWords;
		}

		#endregion Stop words

		#region Provider Settings

		protected string FallBackProviderName { get; private set; }

		internal bool UseFallBackProvider { get {
			return !string.IsNullOrEmpty(this.FallBackProviderName)
				&& null != this.FallBackProvider;
		} }

		internal BlogProvider FallBackProvider {
			get {
				return BlogService.Providers[this.FallBackProviderName];
			}
		}

		#endregion Provider Settings
		
		public override void Initialize(string name, NameValueCollection config)
		{
			base.Initialize(name, config);

			this.FallBackProviderName = config["fallBackProvider"];
		}
	}
}
